<template>
  <div>  <!-- 创建自定义指令 v-loading 当isLoading为true时显示加载蒙层，false时移除蒙层 -->
  <div class="box1" v-loading="isLoading1">
    <ul>
      <li v-for="(item, index) in news" :key="item.id">
        {{ item.name }}- {{ index + 1 }}
      </li>
    </ul>
  </div>
  <!-- 创建自定义指令 v-loading 指令可以复用 -->
  <div class="box2" v-loading="isLoading2">
    <ul>
      <li v-for="(item, index) in news2" :key="item.id">
        {{ item.name }}- {{ index + 1 }}
      </li>
    </ul>
  </div>
</div>

</template>

<script>
export default {
  data() {
    return {
      news: [],
      news2:[],
      isLoading1: true,
      isLoading2:true
    };
  },
  created() {
    setTimeout(() => {
      this.news = [
        { id: 1, name: "张三" },
        { id: 2, name: "李四" },
        { id: 3, name: "王五" },
      ];
      // 数据加载完成后 ，将加载蒙层移除
      this.isLoading1 = false
    }, 3000);
        setTimeout(() => {
      this.news2 = [
        { id: 1, name: "张三" },
        { id: 2, name: "李四" },
        { id: 3, name: "王五" },
      ];
      // 数据加载完成后 ，将加载蒙层移除
      this.isLoading2 = false
    }, 2000);
  },
  directives: {
    // 指令名：指令配置项
    loading: {
      inserted(el, binding) {
        console.log("页面一开始加载时显示 是否加载", binding.value);
        binding.value
          ? el.classList.add("loading")
          : el.classList.remove("loading");
      },
      update(el, binding) {
        // 如果数据没有加载好 isLoading是true，加载好后 移除蒙层
        binding.value
          ? el.classList.add("loading")
          : el.classList.remove("loading");
      },
    },
  },
};
</script>

<style>
/* 第一步：准备loading类 创建loading蒙层*/
.loading::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #fff url("./assets/loading.gif") no-repeat center;
}
.box1{
  width:400px;
  height: 400px;
  border:2px solid #000;
  position:relative;
}
.box2{
  width: 800px;
  min-height: 500px;
  border:3px solid orange;
  position:relative;
}
</style>